package com.css.fxfzypg.modules.resultManagement.reportManagement.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.css.fxfzypg.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzypg.base.attachment.repository.AttachmentInfoRepository;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.manage.building.repository.BuildingReqository;
import com.css.fxfzypg.manage.building.vo.BuildingEntityVO;
import com.css.fxfzypg.manage.sampling.repository.SamplingReqository;
import com.css.fxfzypg.manage.sampling.repository.entity.SamplingEntity;
import com.css.fxfzypg.modules.baseData.entity.*;
import com.css.fxfzypg.modules.baseData.repository.*;
import com.css.fxfzypg.modules.maps.service.GasstationDataMapService;
import com.css.fxfzypg.modules.maps.service.GeologicalMapService;
import com.css.fxfzypg.modules.maps.service.ReservoirMapService;
import com.css.fxfzypg.modules.maps.service.RiskEnterpriseMapService;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.resultManagement.reportManagement.VO.FieldReportManagementVO;
import com.css.fxfzypg.modules.resultManagement.reportManagement.VO.ReportManagementVO;
import com.css.fxfzypg.modules.resultManagement.reportManagement.entity.*;
import com.css.fxfzypg.modules.resultManagement.reportManagement.repository.SamplingSurveyReportRepository;
import com.css.fxfzypg.modules.resultManagement.reportManagement.service.SamplingSurveyReportService2;
import com.css.fxfzypg.modules.resultsManagement.service.MapManagementService;
import com.css.fxfzypg.modules.surveytaskmanage.entity.FieldSurveyTaskEntity;
import com.css.fxfzypg.modules.surveytaskmanage.repository.FieldSurveyTaskRepository;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.plugin.table.HackLoopTableRenderPolicy;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2022年12月08日  14:02
 */
@Service
public class SamplingSurveyReportServiceImpl2 implements SamplingSurveyReportService2 {

    @Value("${image.localDir}")
    private String localDir;

    @Resource
    SUserService sUserService;

    @Resource
    private SamplingSurveyReportRepository samplingSurveyReportRepository;

    @Resource
    private SamplingReqository samplingReqository;

    @Resource
    private HosPeoRepository hosPeoRepository;

    @Resource
    private VillageTownHosPeoRepository villageTownHosPeoRepository;

    @Resource
    private CountiesConditionRepository countiesConditionRepository;

    @Resource
    private VillageTownConditionRepository villageTownConditionRepository;

    @Resource
    private GeologicalMapService geologicalMapService;

    @Resource
    private RiskEnterpriseMapService riskEnterpriseMapService;

    @Resource
    private GasstationDataMapService gasstationDataMapService;

    @Resource
    private ReservoirMapService reservoirMapService;

    @Resource
    SeismicSetoutRepository seismicSetoutRepository;

    @Resource
    private FieldSurveyTaskRepository fieldSurveyTaskRepository;

    @Autowired
    private AttachmentInfoService attachmentInfoService;

    @Resource
    BuildingReqository buildingReqository;

    @Resource
    private AttachmentInfoRepository attachmentInfoRepository;

    @Resource
    private MapManagementService mapManagementService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse createReport(String taskCode,String taskName,String modelName,String attachId, HttpServletResponse response) throws Exception {
        //--生成报告逻辑开始
        //获取图片图件信息
        StringBuilder msg = new StringBuilder();
        List<String> taskNumList = new ArrayList<>();
        FieldSurveyTaskEntity task = fieldSurveyTaskRepository.getParentTask(taskCode);
        //判断是否存在子任务
        List<FieldSurveyTaskEntity> taskList = fieldSurveyTaskRepository.getSubTaskByTaskCode(taskCode);
        if(PlatformObjectUtils.isEmpty(taskList) || taskList.size()==0){
            taskList = new ArrayList<>();
            taskList.add(task);
            taskNumList.add(task.getTaskNum());
        }else{
            taskNumList = taskList.stream().map(FieldSurveyTaskEntity::getTaskNum).collect(Collectors.toList());
        }
        //获取图件图片  不管是详本简本还是现场调查都是取的父任务的图件
        Map<String, String> picMap = mapManagementService.getPathByLabel(task.getId());
        List<Map<String, PictureRenderData>> disaterPictureList = new ArrayList<>();
        List<Map<String, PictureRenderData>> firePicPictureList = new ArrayList<>();
        List<Map<String, PictureRenderData>> reservoirPictureList = new ArrayList<>();
        if(picMap!=null){
            Map<String, PictureRenderData> disaterPictureMap = new HashMap<>();
            if(PlatformObjectUtils.isNotEmpty( picMap.get("7"))){
                disaterPictureMap.put("picture",new PictureRenderData(500, 300, picMap.get("7")));
            }else{
                disaterPictureMap.put("picture",null);
            }
            disaterPictureList.add(disaterPictureMap);

            Map<String, PictureRenderData> firePicPictureMap = new HashMap<>();
            if(PlatformObjectUtils.isNotEmpty( picMap.get("17"))){
                firePicPictureMap.put("picture",new PictureRenderData(500, 300, picMap.get("17")));
            }else{
                firePicPictureMap.put("picture",null);
            }
            firePicPictureList.add(firePicPictureMap);

            Map<String, PictureRenderData> reservoirPictureMap = new HashMap<>();
            if(PlatformObjectUtils.isNotEmpty( picMap.get("18"))){
                reservoirPictureMap.put("picture",new PictureRenderData(500, 300, picMap.get("18")));
            }else{
                reservoirPictureMap.put("picture",null);
            }
            reservoirPictureList.add(reservoirPictureMap);
        }
        Map<String,List<SamplingEntity>> streetMap = new HashMap<>();
        Map<String,List<SamplingEntity>> villageMap = new HashMap<>();
        List<SamplingSurveyReport> reportList = new ArrayList<>();
        Map<String, Object> paramMap = new HashMap<>();
        String provinceName = "";
        //查询该任务code有无子任务，如果有子任务则获取所有子任务下的所有的调研点信息，如果不存在子任务则获取该任务下关联的调研点
        List<SamplingEntity> samplingEntityList = samplingReqository.getSamplingEntityList(taskNumList);
        //构建1-1 调研点信息表
        List<Map<String,Object>> samplingEntityMapList = new ArrayList<Map<String,Object>>();
        //构建调查点概况区县信息
        List<SamplingArea> areaList = new ArrayList<>();
        List<SamplingArea2> areaList2 = new ArrayList<>();
        List<SamplingArea3> areaList3 = new ArrayList<>();
        List<SamplingArea4> areaList4 = new ArrayList<>();
        List<SamplingArea5> areaList5 = new ArrayList<>();
        List<SamplingArea6> areaList6 = new ArrayList<>();
        List<SamplingArea7> areaList7 = new ArrayList<>();
        if(PlatformObjectUtils.isNotEmpty(samplingEntityList)){
            for (SamplingEntity samplingEntity : samplingEntityList) {
                if(streetMap.containsKey(samplingEntity.getProvince()+"_"+ samplingEntity.getCity()+"_"+samplingEntity.getArea())){
                    List<SamplingEntity> streetList = streetMap.get(samplingEntity.getProvince()+"_"+ samplingEntity.getCity()+"_"+samplingEntity.getArea());
                    streetList.add(samplingEntity);
                }else{
                    List<SamplingEntity> steetList = new ArrayList<>();
                    steetList.add(samplingEntity);
                    streetMap.put(samplingEntity.getProvince()+"_"+ samplingEntity.getCity()+"_"+samplingEntity.getArea(),steetList);
                }
                if(villageMap.containsKey(samplingEntity.getProvince()+"_"+ samplingEntity.getCity()+"_"+samplingEntity.getArea()+"_"+samplingEntity.getTownship())){
                    List<SamplingEntity> surveyList = villageMap.get(samplingEntity.getProvince()+"_"+ samplingEntity.getCity()+"_"+samplingEntity.getArea()+"_"+samplingEntity.getTownship());
                    surveyList.add(samplingEntity);
                }else{
                    List<SamplingEntity> surveyList = new ArrayList<>();
                    surveyList.add(samplingEntity);
                    villageMap.put(samplingEntity.getProvince()+"_"+ samplingEntity.getCity()+"_"+samplingEntity.getArea()+"_"+samplingEntity.getTownship(),surveyList);
                }
            }
            int y =1;
            int z =2;
            int db = 1;
            int w =3;
            int aa =4;
            int cc =1;
            int dd =2;
            int ee =3;
            int ff = 6;
            int ddd = 1;
            provinceName = samplingEntityList.get(0).getProvince();
            Map<String,String> areaMap = new HashMap<>();
            AtomicInteger atomicInteger4 = new AtomicInteger(1);
            for (int i = 0; i < samplingEntityList.size(); i++) {
                if(!areaMap.containsKey(samplingEntityList.get(i).getProvince()+"_"+samplingEntityList.get(i).getCity()+"_"+samplingEntityList.get(i).getArea())){
                    areaMap.put(samplingEntityList.get(i).getProvince()+"_"+samplingEntityList.get(i).getCity()+"_"+samplingEntityList.get(i).getArea(),"1");
                    SamplingArea area = new SamplingArea();
                    SamplingArea2 area2 = new SamplingArea2();
                    SamplingArea3 area3 = new SamplingArea3();
                    SamplingArea4 area4 = new SamplingArea4();
                    SamplingArea5 area5 = new SamplingArea5();
                    SamplingArea6 area6 = new SamplingArea6();
                    SamplingArea7 area7 = new SamplingArea7();
                    //查询区县人口和建筑物概况信息
                    HosPeoEntity hosPeo = hosPeoRepository.findHosPeo(samplingEntityList.get(i).getProvince(), samplingEntityList.get(i).getCity(), samplingEntityList.get(i).getArea());
                    if(PlatformObjectUtils.isEmpty(hosPeo)){
                        //return RestResponse.fail(samplingEntityList.get(i).getProvince()+samplingEntityList.get(i).getCity()+samplingEntityList.get(i).getArea()+"的【人口和建筑物概况】未维护。，请到【统计数据管理】模块中维护。");
                        msg.append(samplingEntityList.get(i).getProvince()).append(samplingEntityList.get(i).getCity()).append(samplingEntityList.get(i).getArea()).append("的【人口和建筑物概况】未维护。。");
                    }
                    //查询区县概况信息
                    CountiesCondition countiesCondition = countiesConditionRepository.getQxCountiesCodition(samplingEntityList.get(i).getProvince(), samplingEntityList.get(i).getCity(), samplingEntityList.get(i).getArea());
                    if(PlatformObjectUtils.isEmpty(countiesCondition)){
                        //return RestResponse.fail(samplingEntityList.get(i).getProvince()+samplingEntityList.get(i).getCity()+samplingEntityList.get(i).getArea()+"【综合概况信息】未维护。，请到【统计数据管理】模块中维护。");
                        msg.append(samplingEntityList.get(i).getProvince()).append(samplingEntityList.get(i).getCity()).append(samplingEntityList.get(i).getArea()).append("【综合概况信息】未维护。");
                    }
                    area.setAreaNameTitle(y+"."+(db)+samplingEntityList.get(i).getArea());
                    area.setAreaNameBody(samplingEntityList.get(i).getArea());
                    area2.setAreaNameTitle(z+"."+(db)+samplingEntityList.get(i).getArea());
                    area2.setTownNameBody(samplingEntityList.get(i).getTownship());
                    area2.setAreaNameBody(samplingEntityList.get(i).getArea());
                    area2.setHouseFeature(z+"."+(db)+"."+y+"."+"房屋特点");
                    area2.setEvaluationContent(z+"."+(db)+"."+(y+1)+"."+"抗震能力评价");
                    area2.setHouseStructure(z+"."+(db)+"."+(y+1)+"."+(ddd++)+"."+"房屋结构方面");
                    area2.setHouseAge(z+"."+(db)+"."+(y+1)+"."+(ddd++)+"."+"房屋建造年代方面");
                    area2.setHouseEarthQuake(z+"."+(db)+"."+(y+1)+"."+(ddd++)+"."+"房屋抗震性能方面");
                    area3.setAreaNameTitle(w+"."+(db)+samplingEntityList.get(i).getArea());
                    area3.setAreaNameBody(samplingEntityList.get(i).getArea());
                    area4.setAreaNameTitle(aa+"."+(cc)+"."+atomicInteger4.get()+samplingEntityList.get(i).getArea());
                    area4.setAreaNameBody(samplingEntityList.get(i).getArea());
                    area5.setAreaNameTitle(aa+"."+(dd)+"."+atomicInteger4.get()+samplingEntityList.get(i).getArea());
                    area5.setAreaNameBody(samplingEntityList.get(i).getArea());
                    area6.setAreaNameTitle(aa+"."+(ee)+"."+atomicInteger4.get()+samplingEntityList.get(i).getArea());
                    area7.setAreaNameTitle(ff+"."+atomicInteger4.get()+samplingEntityList.get(i).getArea());
                    area7.setAreaNameBody(samplingEntityList.get(i).getArea());
                    atomicInteger4 = new AtomicInteger(atomicInteger4.incrementAndGet());
                    if( PlatformObjectUtils.isNotEmpty(hosPeo)){
                        //获取调查点概况城镇结构类型占比
                        List<Map<String, Object>> townStructureList = returnAreaTownStructureList(hosPeo);
                        //获取调查点概况农村结构类型占比
                        List<Map<String, Object>> villageStructureList = returnAreaVillageStructureList(hosPeo);
                        area.setArea(String.valueOf(hosPeo.getDhpCountyArea().intValue()));
                        area.setPopulation(String.valueOf(hosPeo.getDhpTotalPop().intValue()));
                        area.setHouseRatio(String.valueOf(hosPeo.getDhpHouseTatio().intValue())+"%");
                        area.setAreaTownStructureList(townStructureList);
                        area.setAreaVillageStructureList(villageStructureList);
                    }
                    if(PlatformObjectUtils.isNotEmpty(countiesCondition)){
                        area.setCcNation(countiesCondition.getCcNation());
                        area.setCcEconomy(countiesCondition.getCcEconomy());
                        area.setCcLandform(countiesCondition.getCcLandform());
                        area.setCcClimate(countiesCondition.getCcClimate());
                        area.setCcSeismotectonics(countiesCondition.getCcSeismotectonics());
                        area.setCcTraffic(countiesCondition.getCcTraffic());
                        area.setCcDisaster(countiesCondition.getCcDisaster());
                        area.setCcFacility(countiesCondition.getCcFacility());
                        area.setCcHistory(countiesCondition.getCcHistory());
                        area.setCcTrait(countiesCondition.getCcTrait());
                        area.setCcHazard(countiesCondition.getCcHazard());
                        area.setCcReservoir(countiesCondition.getCcReservoir());
                    }
                    area.setProvince(samplingEntityList.get(i).getProvince());
                    area.setCity(samplingEntityList.get(i).getCity());
                    areaList.add(area);
                    area2.setProvince(samplingEntityList.get(i).getProvince());
                    area2.setCity(samplingEntityList.get(i).getCity());
                    areaList2.add(area2);
                    area3.setProvince(samplingEntityList.get(i).getProvince());
                    area3.setCity(samplingEntityList.get(i).getCity());
                    area3.setDisaterPictureList(disaterPictureList);
                    areaList3.add(area3);
                    area4.setProvince(samplingEntityList.get(i).getProvince());
                    area4.setCity(samplingEntityList.get(i).getCity());
                    area4.setFirePicPictureList(firePicPictureList);
                    areaList4.add(area4);
                    area5.setProvince(samplingEntityList.get(i).getProvince());
                    area5.setCity(samplingEntityList.get(i).getCity());
                    area5.setReservoirPictureList(reservoirPictureList);
                    areaList5.add(area5);
                    areaList6.add(area6);
                    area7.setProvince(samplingEntityList.get(i).getProvince());
                    area7.setCity(samplingEntityList.get(i).getCity());
                    areaList7.add(area7);
                    db++;
                }
                Map<String,Object> map = new HashMap<String, Object>();
                //省
                map.put("province", samplingEntityList.get(i).getProvince());
                //县
                map.put("area", samplingEntityList.get(i).getArea());
                //乡镇
                map.put("township",samplingEntityList.get(i).getTownship());
                //调研点名称
                map.put("surveyName",samplingEntityList.get(i).getFieldSurveyName());
                samplingEntityMapList.add(map);
            }
        }else{
            msg.append(taskCode).append("没有关联调研点信息");
        }

        if(PlatformObjectUtils.isNotEmpty(areaList)){
            AtomicInteger tableInteger = new AtomicInteger(1);
            for (int i = 0; i < areaList.size(); i++) {
                areaList.get(i).setTownTableIndex(""+tableInteger.getAndAdd(1));
                areaList.get(i).setVillageTableIndex(""+tableInteger.getAndIncrement());
                List<SamplingEntity> samplingEntities = streetMap.get(areaList.get(i).getProvince() + "_" + areaList.get(i).getCity() + "_" + areaList.get(i).getAreaNameBody());
//                for(SamplingEntity entity:samplingEntities){
//                    VillageTownHosPeoEntity villageTownHosPeo = villageTownHosPeoRepository.findHosPeo(entity.getProvince(),entity.getCity(),entity.getArea(),entity.getTownship());
//                    if (PlatformObjectUtils.isEmpty(villageTownHosPeo)){
//                        //return RestResponse.fail(entity.getProvince()+entity.getCity()+entity.getArea()+entity.getTownship()+"的【人口和建筑物概况】未维护。，请到【统计数据管理】模块中维护。");
//                        msg.append(entity.getProvince()).append(entity.getCity()).append(entity.getArea()).append(entity.getTownship()).append("的【人口和建筑物概况】未维护。");
//                    }
//                    //查询乡镇概况信息
//                    VillageTownCondition villageCountiesCodition = villageTownConditionRepository.getVillageCountiesCodition(entity.getProvince(),entity.getCity(),entity.getArea(),entity.getTownship());
//                    if(PlatformObjectUtils.isEmpty(villageCountiesCodition)){
//                        //return RestResponse.fail(entity.getProvince()+entity.getCity()+entity.getArea()+entity.getTownship()+"的【综合概况信息】未维护。，请到【统计数据管理】模块中维护。");
//                        msg.append(entity.getProvince()).append(entity.getCity()).append(entity.getArea()).append(entity.getTownship()).append("的【综合概况信息】未维护。");
//                    }
//                };

                if(PlatformObjectUtils.isNotEmpty(samplingEntities)){
                    Map<String,String> map = new HashMap<>();
                    for (SamplingEntity samplingEntity : samplingEntities) {
                        map.put(samplingEntity.getProvince()+"_"+samplingEntity.getCity()+"_"+samplingEntity.getArea()+"_"+samplingEntity.getTownship(),"1");
                    }
                    List<SamplingTown> townList = new ArrayList<>();
                    if(map.values().size()>0){
                        AtomicInteger yy= new AtomicInteger(1);
                        String areaNameTitle = areaList.get(i).getAreaNameTitle();
                        char[] chars = areaNameTitle.toCharArray();

                        map.forEach((k,v)->{
                            StringBuilder builder = new StringBuilder("");
                            StringBuilder append = builder.append(chars[0]).append(chars[1]).append(chars[2]);
                            int i2 = yy.get();
                            String index = append.append(".").append(i2).toString();
                            SamplingTown town = new SamplingTown();
                            town.setTownNameTitle(index+k.split("_")[3]).setTownNameBody(k.split("_")[3])
                                    .setProvince(k.split("_")[0])
                                    .setCity(k.split("_")[1])
                                    .setAreaName(k.split("_")[2]);
                            VillageTownHosPeoEntity villageHosPeo = villageTownHosPeoRepository.findHosPeo(k.split("_")[0], k.split("_")[1], k.split("_")[2],k.split("_")[3]);
                            if(PlatformObjectUtils.isEmpty(villageHosPeo)){
                                msg.append(k.split("_")[0]).append(k.split("_")[1]).append(k.split("_")[2]).append(k.split("_")[3]).append("的人口和建筑物概况信息未维护。");
                            }else{
                                List<Map<String, Object>> townStructureList = returnTownStructureList(villageHosPeo);
                                List<Map<String, Object>> villageStructureList = returnVillageStructureList(villageHosPeo);
                                town.setArea(villageHosPeo.getDhpCountyArea().toString()).setPopulation(String.valueOf(villageHosPeo.getDhpTotalPop().intValue())).setHouseRatio(String.valueOf(villageHosPeo.getDhpHouseTatio().intValue())+"%")
                                        .setTownStructureList(townStructureList)
                                        .setVillageStructureList(villageStructureList);
                            }
                            //查询乡镇概况信息
                            VillageTownCondition villageTownCondition = villageTownConditionRepository.getVillageCountiesCodition(k.split("_")[0], k.split("_")[1], k.split("_")[2],k.split("_")[3]);
                            if(PlatformObjectUtils.isEmpty(villageTownCondition)){
                                msg.append(k.split("_")[0]).append(k.split("_")[1]).append(k.split("_")[2]).append(k.split("_")[3]).append("的【乡镇概况信息】未维护。");
                            }else{
                                town.setCcNation(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcNation());
                                town.setCcEconomy(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcEconomy());
                                town.setCcLandform(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcLandform());
                                town.setCcClimate(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcClimate());
                                town.setCcSeismotectonics(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcSeismotectonics());
                                town.setCcTraffic(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcTraffic());
                                town.setCcDisaster(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcDisaster());
                                town.setCcFacility(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcFacility());
                                town.setCcTrait(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcTrait());
                                town.setCcHazard(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcHazard());
                                town.setCcReservoir(PlatformObjectUtils.isEmpty(villageTownCondition)?"":villageTownCondition.getCcReservoir());
                            }
                            town.setTownTableIndex(""+tableInteger.getAndIncrement());
                            town.setVillageTableIndex(""+tableInteger.getAndIncrement());
                            List<SamplingEntity> villageList = villageMap.get(town.getProvince()+"_"+ town.getCity()+"_"+town.getAreaName()+"_"+town.getTownNameBody());
                            List<SamplingVillage> samplingVillageList = new ArrayList<>();
                            if(PlatformObjectUtils.isNotEmpty(villageList)){
                                for (int i1 = 0; i1 < villageList.size(); i1++) {
                                    SamplingVillage samplingVillage = new SamplingVillage();
                                    String text = "";
                                    if("是".equals(villageList.get(i1).getIsDisaster())){
                                        if(StringUtils.isNotBlank(villageList.get(i1).getDisasterScale())){
                                            text+=villageList.get(i1).getDisasterScale();
                                        }
                                        if(StringUtils.isNotBlank(villageList.get(i1).getDisasterType())){
                                            text+=villageList.get(i1).getDisasterType();
                                        }
                                    }
                                    text+="地质灾害点";
                                    samplingVillage.setVillageNameTitle(index+"."+(i1+1)+villageList.get(i1).getFieldSurveyName()).setVillageNamebody(villageList.get(i1).getFieldSurveyName())
                                            .setTownName(villageList.get(i1).getTownship()).setHouseNum(villageList.get(i1).getTotalHouseholdNum())
                                            .setPopulation(villageList.get(i1).getTotalPopulation()).setResident(villageList.get(i1).getActualResidentPopulation())
                                            .setOuter(villageList.get(i1).getMigrantWorkers()).setChild(villageList.get(i1).getChildrenProportion())
                                            .setAuditNum(villageList.get(i1).getYoungProportion()).setOldNum(villageList.get(i1).getOldAgeProportion())
                                            .setLoadStatus(villageList.get(i1).getTrafficConditions()).setLocation(villageList.get(i1).getEnvironment())
                                            .setSchoolStatus("是".equals(villageList.get(i1).getIsSchool())?"有学校，学生数量约"+(StringUtils.isNotBlank(villageList.get(i1).getStudentNum())?villageList.get(i1).getStudentNum():"")+"人，教室"+(StringUtils.isNotBlank(villageList.get(i1).getClassroomNum())?villageList.get(i1).getClassroomNum():"")+"间":"无学校")
                                            .setHospital("是".equals(villageList.get(i1).getIsHospital())?"有医院，医生"+(StringUtils.isNotBlank(villageList.get(i1).getDoctorNum())?villageList.get(i1).getDoctorNum():"")+"名，床位数"+(StringUtils.isNotBlank(villageList.get(i1).getBedNum())?villageList.get(i1).getBedNum():"")+"个":"无医院")
//                                            .setSchoolStatus("是".equals(villageList.get(i1).getIsSchool())?"有学校，学生数量约"+villageList.get(i1).getStudentNum()+"人，教室"+villageList.get(i1).getClassroomNum()+"间":"无学校")
//                                            .setHospital("是".equals(villageList.get(i1).getIsHospital())?"有医院，医生"+villageList.get(i1).getDoctorNum()+"名，床位数"+villageList.get(i1).getBedNum()+"个":"无医院")
                                            .setDisasterPoint("是".equals(villageList.get(i1).getIsDisaster())?"有"+text:"无"+text)
                                            //.setDisasterPoint("是".equals(villageList.get(i1).getIsDisaster())?"有":"无"+(StringUtils.isNotBlank(villageList.get(i1).getDisasterScale())?villageList.get(i1).getDisasterScale():"")+(PlatformObjectUtils.isNotEmpty(villageList.get(i1).getDisasterType())?villageList.get(i1).getDisasterType():""))
                                            .setReser("是".equals(villageList.get(i1).getIsReservoir())?"有水库":"无水库");
                                    samplingVillageList.add(samplingVillage);
                                }
                            }
                            town.setVillageList(samplingVillageList);
                            yy.getAndIncrement();
                            townList.add(town);
                        });
                        areaList.get(i).setTownList(townList);
                    }
                }
            }
        }
        if(PlatformObjectUtils.isNotEmpty(areaList2)){
            for (int i = 0; i < areaList2.size(); i++) {
                List<SamplingEntity> samplingEntities = streetMap.get(areaList2.get(i).getProvince() + "_" + areaList2.get(i).getCity() + "_" + areaList2.get(i).getAreaNameBody());
                if(PlatformObjectUtils.isNotEmpty(samplingEntities)){
                    Map<String,SamplingEntity> map = new HashMap<>();
                    for (SamplingEntity samplingEntity : samplingEntities) {
                        map.put(samplingEntity.getProvince()+"_"+samplingEntity.getCity()+"_"+samplingEntity.getArea()+"_"+samplingEntity.getTownship(),samplingEntity);
                    }
                    List<SamplingVillage2> village2List = new ArrayList<>();
                    if(map.values().size()>0){
                        AtomicInteger yy= new AtomicInteger(1);
                        String houseFeature = areaList2.get(i).getHouseFeature();
                        char[] chars = houseFeature.toCharArray();

                        map.forEach((k,v)->{
                            StringBuilder builder = new StringBuilder("");
                            StringBuilder append = builder.append(chars[0]).append(chars[1]).append(chars[2]).append(chars[3]).append(chars[4]);
                            String index = append.append(".").append(yy.getAndAdd(1)).toString();
                            SamplingVillage2 village2 = new SamplingVillage2();
                            village2.setTownNameTitle(index+v.getTownship());
                            village2.setTownNameBody(v.getTownship()).setVillageName(v.getFieldSurveyName());
                            village2.setVillageName(v.getFieldSurveyName());
                            village2.setAreaNameBody(v.getArea());
                            Map<String, Double> doubleStr = buildSortMap(v);
                            Map<String, Double> yearStr = buildSortYearMap(v);
                            StringBuilder mainStructureTypeBuilder = new StringBuilder();
                            StringBuilder conditionBuilder = new StringBuilder();
                            if(doubleStr.values().size()>0){
                                doubleStr.forEach((k1,v1)->{
                                    mainStructureTypeBuilder.append(k1).append("、");
                                    conditionBuilder.append(k1).append("占比约").append(v1).append("%").append(",");
                                });
                            }
                            conditionBuilder.append("房屋建造年代情况：");
                            if(yearStr.values().size()>0){
                                yearStr.forEach((k1,v1)->{
                                    conditionBuilder.append(k1).append("占比约").append(v1).append("%").append(",");
                                });
                            }
                            String mainStructureType = mainStructureTypeBuilder.length()>0?mainStructureTypeBuilder.toString():"";
                            mainStructureType = StringUtils.isNotBlank(mainStructureType)?mainStructureType.substring(0,mainStructureType.length()-1):"";
                            String structureCondition = conditionBuilder.length()>0?conditionBuilder.toString():"";
                            structureCondition = StringUtils.isNotBlank(structureCondition)?structureCondition.substring(0,structureCondition.length()-1):"";
                            village2.setStructureStyle(mainStructureType).setStructureCondition(structureCondition);
                            List<BuildingStructure> structureList = new ArrayList<>();
                            Map<String, Object> futureStr = buildFutureMap(v);
                            AtomicInteger kk= new AtomicInteger(1);
                            futureStr.forEach((k11,v11)->{
                                BuildingStructure buildingStructure = new BuildingStructure();
                                buildingStructure.setStructureName("（"+kk+"） "+k11);
                                String type = "";
                                if("高层结构".equals(k11)) {
                                    buildingStructure.setStructureFeature("  "+v11);
                                    type = "0";
                                }
                                if("钢结构".equals(k11)) {
                                    buildingStructure.setStructureFeature("  "+v11);
                                    type = "1";
                                }
                                if("多层钢筋混凝土结构".equals(k11)) {
                                    buildingStructure.setStructureFeature("  "+v11);
                                    type = "2";
                                }
                                if("砖混结构".equals(k11)) {
                                    buildingStructure.setStructureFeature("  "+v11);
                                    type = "3";
                                }
                                if("砖木结构".equals(k11)) {
                                    buildingStructure.setStructureFeature("  "+v11);
                                    type = "4";
                                }
                                if("土结构".equals(k11)) {
                                    buildingStructure.setStructureFeature("  "+v11);
                                    type = "5";
                                }
                                if("木结构".equals(k11)) {
                                    buildingStructure.setStructureFeature("  "+v11);
                                    type = "6";
                                }
                                if("石结构".equals(k11)) {
                                    buildingStructure.setStructureFeature("  "+v11);
                                    type = "7";
                                }
                                if("其他结构".equals(k11)) {
                                    buildingStructure.setStructureFeature("  "+v11);
                                    type = "8";
                                }
                                List<BuildingEntityVO> buildingEntityList = buildingReqository.queryBuildingEntityData( v.getProvince(), v.getCity(), v.getArea(), v.getFieldSurveyName(),type);
                                List<AttachmentInfoEntity> structurePicList = null;
                                List<Map<String, PictureRenderData>> picList = new ArrayList<>();
                                if(buildingEntityList!=null){
                                    for (BuildingEntityVO buildingEntity : buildingEntityList) {
                                        if(StringUtils.isNotEmpty(buildingEntity.getSpecifyPicture())){
                                            structurePicList = attachmentInfoRepository.findInIdList(Arrays.asList(buildingEntity.getSpecifyPicture().split(",")));
                                            if(PlatformObjectUtils.isNotEmpty(structurePicList)){
                                                for(AttachmentInfoEntity entity:structurePicList){
                                                    Map<String, PictureRenderData> pictureMap = new HashMap<>();
                                                    pictureMap.put("picture", new PictureRenderData(255, 160, entity.getFileDirId()+entity.getAttachPath()));
                                                    picList.add(pictureMap);
                                                };
                                            }
                                        }
                                    }
//                                    Map<String, PictureRenderData> pictureMap = new HashMap<>();
//                                    pictureMap.put("picture", new PictureRenderData(255, 160, "D:\\static\\1.jpg"));
//                                    picList.add(pictureMap);
//                                    pictureMap = new HashMap<>();
//                                    pictureMap.put("picture", new PictureRenderData(255, 160, "D:\\static\\2.jpg"));
//                                    picList.add(pictureMap);
//                                    pictureMap = new HashMap<>();
//                                    pictureMap.put("picture", new PictureRenderData(255, 160, "D:\\static\\3.jpg"));
//                                    picList.add(pictureMap);
//                                    pictureMap = new HashMap<>();
//                                    pictureMap.put("picture", new PictureRenderData(255, 160, "D:\\static\\5.jpg"));
//                                    picList.add(pictureMap);
                                }
                                buildingStructure.setStructurePicList(picList);
                                structureList.add(buildingStructure);
                                kk.getAndIncrement();
                            });
                            String typePieId = v.getTypePieId();
                            String yearsPieId = v.getYearsPieId();
                            List<Map<String, PictureRenderData>> mapList = new ArrayList<>();
                            if("".equals(typePieId) && "".equals(yearsPieId)){
                                Map<String, PictureRenderData> pictureMap = new HashMap<>();
                                pictureMap.put("picture", null);
                                mapList.add(pictureMap);
                            }else{
                                List<AttachmentInfoEntity> dcdPicList = attachmentInfoRepository.findInIdList(Arrays.asList(typePieId,yearsPieId));
                                if(PlatformObjectUtils.isNotEmpty(dcdPicList)){
                                    for(AttachmentInfoEntity entity:dcdPicList){
                                        Map<String, PictureRenderData> pictureMap = new HashMap<>();
                                        pictureMap.put("picture", new PictureRenderData(255, 160, entity.getFileDirId()+entity.getAttachPath()));
                                        mapList.add(pictureMap);
                                    };
                                }
                            }
//                            Map<String, PictureRenderData> pictureMap = new HashMap<>();
//                            pictureMap.put("picture", new PictureRenderData(255, 160, "D:\\static\\1.jpg"));
//                            mapList.add(pictureMap);
//                            pictureMap = new HashMap<>();
//                            pictureMap.put("picture", new PictureRenderData(255, 160, "D:\\static\\2.jpg"));
//                            mapList.add(pictureMap);
                            village2.setDcdPictures(mapList);
                            village2.setStructureList(structureList);
                            //yy.getAndIncrement();
                            village2List.add(village2);
                        });
                        areaList2.get(i).setVillage2List(village2List);
                    }
                }
            }
        }
        if(PlatformObjectUtils.isNotEmpty(areaList3)){
            AtomicInteger atomicInteger = new AtomicInteger(1);
            AtomicInteger tableInteger = new AtomicInteger(1);
            for (int i = 0; i < areaList3.size(); i++) {
                SamplingArea3 samplingArea3 = areaList3.get(i);
                List<Map<String,Object>> staticsMapList = new ArrayList<>();
                List<GeologicalEntity> geologicalEntityList = geologicalMapService.getAllData(areaList3.get(i).getProvince() , areaList3.get(i).getCity() , areaList3.get(i).getAreaNameBody());
                if(PlatformObjectUtils.isNotEmpty(geologicalEntityList)){
                    long count = geologicalEntityList.size();
                    samplingArea3.setDisaterPointNum(String.valueOf(count));
                    Map<String, List<GeologicalEntity>> collect = geologicalEntityList.stream().collect(Collectors.groupingBy(GeologicalEntity::getDgdDisasterType));
                    StringBuilder builder = new StringBuilder();
                    collect.forEach((k,v)->{
                        builder.append(k).append("隐患点").append(v.size()).append("处").append("、");
                    });
                    String s = builder.toString();
                    s = s.length()>0?s.substring(0,s.length()-1):"";
                    samplingArea3.setDisaterPointDetails(s);
                    //int sum = geologicalEntityList.stream().mapToInt(GeologicalEntity::getDgdImpactPeoNum).sum();
                    int sum = geologicalEntityList.stream().mapToInt(g -> Objects.isNull(g.getDgdImpactPeoNum()) ? 0 : g.getDgdImpactPeoNum()).sum();
                    samplingArea3.setAffectedPeopleNum(String.valueOf(sum));
                    //int houseNum = geologicalEntityList.stream().mapToInt(GeologicalEntity::getDgdImpactHouseNum).sum();
                    int houseNum = geologicalEntityList.stream().mapToInt(g -> Objects.isNull(g.getDgdImpactHouseNum()) ? 0 : g.getDgdImpactHouseNum()).sum();
                    samplingArea3.setAffectedHouseNum(String.valueOf(houseNum));
                    Map<String, List<GeologicalEntity>> levelMap = geologicalEntityList.stream().collect(Collectors.groupingBy(GeologicalEntity::getDgdDangerLevel));
                    StringBuilder levelBuilder = new StringBuilder();
                    levelMap.forEach((k,v)->{
                        levelBuilder.append(k).append(v.size()).append("处、");
                    });
                    String level = levelBuilder.toString();
                    level = level.length()>0?level.substring(0,level.length()-1):"";
                    samplingArea3.setDisaterLevelDetails(level);
                    Map<String, String> mostMap = geologicalEntityList.stream().filter(geologicalEntity -> "特大型".equals(geologicalEntity.getDgdDangerLevel()) ).collect(Collectors.toMap(GeologicalEntity::getId, GeologicalEntity::getDgdName));
                    StringBuilder mostBuilder = new StringBuilder();
                    String substring = "";
                    if(mostMap.values().size()>0){
                        mostBuilder.append("险情等级为特大型的隐患点有");
                        mostMap.forEach((k,v)->{
                            mostBuilder.append(v).append("、");
                        });
                        substring = mostBuilder.substring(0, mostBuilder.length() - 1);
                    }

                    Map<String, String> seriousMap = geologicalEntityList.stream().filter(geologicalEntity -> "大型".equals(geologicalEntity.getDgdDangerLevel()) ).collect(Collectors.toMap(GeologicalEntity::getId, GeologicalEntity::getDgdName));
                    StringBuilder seriousBuilder = new StringBuilder();
                    String seriousDetails = "";
                    if(seriousMap.values().size()>0){
                        if(StringUtils.isNotBlank(substring)){
                            seriousBuilder.append(substring).append(";");
                        }
                        seriousBuilder.append("险情等级为大型的隐患点有");
                        seriousMap.forEach((k,v)->{
                            seriousBuilder.append(v).append("、");
                        });
                        seriousDetails = seriousBuilder.substring(0, seriousBuilder.length() - 1);
                    }
                    samplingArea3.setSeriousDetails(seriousDetails);
                    geologicalEntityList.forEach(geologicalEntity -> {
                        Map<String,Object> staticsMap = new HashMap<>();
                        staticsMap.put("num",atomicInteger.getAndAdd(1));
                        String dgdName = geologicalEntity.getDgdName();
                        staticsMap.put("dgdName",dgdName);
                        staticsMap.put("dgdType",geologicalEntity.getDgdDisasterType());
                        staticsMap.put("dgdLocation",geologicalEntity.getDgdName());
                        staticsMap.put("dgdLevel",geologicalEntity.getDgdDangerLevel());
                        staticsMapList.add(staticsMap);
                    });
                    samplingArea3.setStatisticsList(staticsMapList);
                }else{
                   msg.append(areaList3.get(i).getProvince()).append(areaList3.get(i).getCity()).append(areaList3.get(i).getAreaNameBody()).append("地质灾害隐患点信息未维护。");
                }
                samplingArea3.setTownTableIndex(""+tableInteger.getAndIncrement());
            }
        }
        if(PlatformObjectUtils.isNotEmpty(areaList4)){
            AtomicInteger tableInteger = new AtomicInteger(1);
            for (int i = 0; i < areaList4.size(); i++) {
                AtomicInteger atomicInteger = new AtomicInteger(1);
                AtomicInteger atomicInteger1 = new AtomicInteger(1);
                SamplingArea4 samplingArea4 = areaList4.get(i);
                List<Map<String,Object>> enterpriseList = new ArrayList<>();
                List<RiskEnterpriseData> geologicalEntityList = riskEnterpriseMapService.getAllData(areaList4.get(i).getProvince() , areaList4.get(i).getCity() , areaList4.get(i).getAreaNameBody());
                if(PlatformObjectUtils.isNotEmpty(geologicalEntityList)){
                    long count = geologicalEntityList.size();
                    samplingArea4.setEnterpriseNum(String.valueOf(count));
                    for (RiskEnterpriseData entity : geologicalEntityList) {
                        Map<String,Object> staticsMap = new HashMap<>();
                        staticsMap.put("num",atomicInteger.getAndAdd(1));
                        staticsMap.put("enterpriseName",entity.getRedName());
                        staticsMap.put("enterpriseAddress",entity.getRedAddress());
                        staticsMap.put("type",entity.getRedType());
                        staticsMap.put("level",entity.getRedRiskgrade());
                        enterpriseList.add(staticsMap);
                    }
                    samplingArea4.setEnterpriseList(enterpriseList);
                }else{
                    msg.append(areaList3.get(i).getProvince()).append(areaList3.get(i).getCity()).append(areaList3.get(i).getAreaNameBody()).append("危化企业信息未维护。");
                }

                List<Map<String,Object>> gasStationList = new ArrayList<>();
                List<GasstationData> allData = gasstationDataMapService.getAllData(areaList4.get(i).getProvince(), areaList4.get(i).getCity(), areaList4.get(i).getAreaNameBody());
                if(PlatformObjectUtils.isNotEmpty(allData)){
                    samplingArea4.setGasStationNum(String.valueOf(allData.size()));
                    for (GasstationData entity : allData) {
                        Map<String,Object> staticsMap = new HashMap<>();
                        staticsMap.put("num",atomicInteger1.getAndAdd(1));
                        staticsMap.put("gasName",entity.getGsName());
                        staticsMap.put("gasAdrress",entity.getGsAddress());
                        staticsMap.put("scale",entity.getGsScale());
                        staticsMap.put("level",entity.getGsRiskgrade());
                        gasStationList.add(staticsMap);
                    }
                    samplingArea4.setGasStationList(gasStationList);
                }else{
                    msg.append(areaList3.get(i).getProvince()).append(areaList3.get(i).getCity()).append(areaList3.get(i).getAreaNameBody()).append("加油站信息未维护。");
                }
//                List<Map<String, PictureRenderData>> picMapList = new ArrayList<>();
//                Map<String, PictureRenderData> pictureMap = new HashMap<>();
//                //pictureMap.put("picture", new PictureRenderData(100, 120, ""));
//                pictureMap.put("picture", null);
//                picMapList.add(pictureMap);
//                samplingArea4.setFirePicPictureList(picMapList);
                samplingArea4.setTownTableIndex(""+tableInteger.getAndIncrement());
                samplingArea4.setVillageTableIndex(""+tableInteger.getAndIncrement());
            }
        }
        if(PlatformObjectUtils.isNotEmpty(areaList5)){
            AtomicInteger tableInteger = new AtomicInteger(2);
            for (int i = 0; i < areaList5.size(); i++) {
                AtomicInteger atomicInteger = new AtomicInteger(1);
                SamplingArea5 samplingArea5 = areaList5.get(i);
                List<Map<String,Object>> staticsList = new ArrayList<>();
                List<ReservoirEntity> reservoirEntityList = reservoirMapService.getAllData(areaList5.get(i).getProvince() , areaList5.get(i).getCity() , areaList5.get(i).getAreaNameBody());
                if(PlatformObjectUtils.isNotEmpty(reservoirEntityList)){
                    List<String> collect = reservoirEntityList.stream().map(ReservoirEntity::getResScale).distinct().collect(Collectors.toList());
                    long count = reservoirEntityList.size();
                    samplingArea5.setReservoirNum(String.valueOf(count));
                    StringBuilder builder = new StringBuilder();
                    if(collect.size()>0){
                        collect.forEach((str)->{
                            builder.append(str).append("、");
                        });
                    }
                    String reservoirType = builder.length()>0?builder.substring(0, builder.length() - 1):"";
                    samplingArea5.setReservoirType(reservoirType);
                    for (ReservoirEntity entity : reservoirEntityList) {
                        Map<String,Object> staticsMap = new HashMap<>();
                        staticsMap.put("num",atomicInteger.getAndAdd(1));
                        staticsMap.put("reservoir",entity.getResName());
                        staticsMap.put("reservoirCapacity",entity.getResCapacity());
                        staticsMap.put("reservoirScale",entity.getResScale());
                        staticsMap.put("reservoirType",entity.getResResultType());
                        staticsList.add(staticsMap);
                    }
                    samplingArea5.setStaticsList(staticsList);
                }else{
                    msg.append(areaList3.get(i).getProvince()).append(areaList3.get(i).getCity()).append(areaList3.get(i).getAreaNameBody()).append("水库信息未维护。");
                }
                samplingArea5.setTownTableIndex(""+tableInteger.getAndIncrement());
            }
        }
        if(PlatformObjectUtils.isNotEmpty(areaList7)){
            AtomicInteger tableInteger = new AtomicInteger(1);
            for (int i = 0; i < areaList7.size(); i++) {
                areaList7.get(i).setIndex1(""+tableInteger.getAndAdd(1));
                areaList7.get(i).setIndex2(""+tableInteger.getAndIncrement());
                areaList7.get(i).setIndex3(""+tableInteger.getAndAdd(1));
                areaList7.get(i).setIndex4(""+tableInteger.getAndIncrement());
                areaList7.get(i).setIndex5(""+tableInteger.getAndAdd(1));
                AtomicInteger atomicInteger = new AtomicInteger(1);
                SamplingArea7 samplingArea7 = areaList7.get(i);
                List<ScSeismicsetout> entityList = seismicSetoutRepository.getAllData(areaList7.get(i).getProvince() , areaList7.get(i).getCity() , areaList7.get(i).getAreaNameBody());
                if(PlatformObjectUtils.isNotEmpty(entityList)){
                    ScSeismicsetout scSeismicsetout = entityList.get(0);
                    samplingArea7.setPlanSystem(scSeismicsetout.getScDzyjzztxhyatx())
                            .setMechanism(scSeismicsetout.getScDzyjgzjz())
                            .setImplementation(scSeismicsetout.getScYjylkzqk())
                            .setSafeguards(scSeismicsetout.getScSmxyjbzqk())
                            .setPrevention(scSeismicsetout.getScCszhffqk())
                            .setMedicalhelp(scSeismicsetout.getScMedicalhelp())
                            .setDemand(scSeismicsetout.getScYjdcxq())
                            .setDevelopment(scSeismicsetout.getScBzxtjsqk())
                            .setSupportability(scSeismicsetout.getScZdmbbznl())
                            .setPublicOpinion(scSeismicsetout.getScYyyqyjnl())
                            .setScience(scSeismicsetout.getScKpxjhyl())
                            .setOther(scSeismicsetout.getScQtdftzyjzbcs());
                    List<ScSupplies> wzList = seismicSetoutRepository.getWz(scSeismicsetout.getScId());
                    List<Map<String,Object>> reservesList = new ArrayList<>();
                    if(PlatformObjectUtils.isNotEmpty(wzList)){
                        wzList.forEach(entity->{
                            Map<String,Object> staticsMap = new HashMap<>();
                        staticsMap.put("num",atomicInteger.getAndAdd(1));
                        staticsMap.put("name",entity.getScSuppliesName());
                        staticsMap.put("brand",entity.getScSuppliesBrand());
                        staticsMap.put("amount",entity.getScSuppliesNumber());
                        staticsMap.put("unit",entity.getScSuppliesUnit());
                        staticsMap.put("note",entity.getScSuppliesNote());
                        reservesList.add(staticsMap);
                        });
                    }
                    samplingArea7.setReservesList(reservesList);
                    AtomicInteger atomicInteger1 = new AtomicInteger(1);
                    List<ScRescue> scRescueList = seismicSetoutRepository.getScRescue(scSeismicsetout.getScId());
                    List<Map<String,Object>> rescueList = new ArrayList<>();
                    if(PlatformObjectUtils.isNotEmpty(scRescueList)){
                        scRescueList.forEach(entity->{
                            Map<String,Object> staticsMap = new HashMap<>();
                            staticsMap.put("num",atomicInteger1.getAndAdd(1));
                            staticsMap.put("name",entity.getScRescueName());
                            staticsMap.put("industry",entity.getScRescueIndustry());
                            staticsMap.put("unit",entity.getScRescueUnit());
                            staticsMap.put("address",entity.getScRescueAddress());
                            staticsMap.put("amount",entity.getScRescueNumber());
                            staticsMap.put("note",entity.getScRescueNote());
                            rescueList.add(staticsMap);
                        });
                    }
                    samplingArea7.setRescueList(rescueList);
                    AtomicInteger atomicInteger2 = new AtomicInteger(1);
                    List<ScEquip> scEquipList = seismicSetoutRepository.getEquip(scSeismicsetout.getScId());
                    List<Map<String,Object>> equipList = new ArrayList<>();
                    if(PlatformObjectUtils.isNotEmpty(scEquipList)){
                        scEquipList.forEach(entity->{
                            Map<String,Object> staticsMap = new HashMap<>();
                            staticsMap.put("num",atomicInteger2.getAndAdd(1));
                            staticsMap.put("name",entity.getScEquipName());
                            staticsMap.put("amount",entity.getScEquipNumber());
                            staticsMap.put("note",entity.getScEquipNote());
                            equipList.add(staticsMap);
                        });
                    }
                    samplingArea7.setEquipList(equipList);
                    AtomicInteger atomicInteger3 = new AtomicInteger(1);
                    List<ScSanctuary> scSanctuaryList = seismicSetoutRepository.getSc(scSeismicsetout.getScId());
                    List<Map<String,Object>> sanctuaryList = new ArrayList<>();
                    if(PlatformObjectUtils.isNotEmpty(scSanctuaryList)){
                        scSanctuaryList.forEach(entity->{
                            Map<String,Object> staticsMap = new HashMap<>();
                            staticsMap.put("num",atomicInteger3.getAndAdd(1));
                            staticsMap.put("amount",entity.getScSanctuaryNumber());
                            staticsMap.put("area",entity.getScSanctuaryArea());
                            staticsMap.put("capacity",entity.getScSanctuaryNumberpeople());
                            sanctuaryList.add(staticsMap);
                        });
                    }
                    samplingArea7.setSanctuaryList(sanctuaryList);
                    AtomicInteger atomicInteger4 = new AtomicInteger(1);
                    List<ScMedical> scScMedicalList = seismicSetoutRepository.getMe(scSeismicsetout.getScId());
                    List<Map<String,Object>> scMedicalList = new ArrayList<>();
                    if(PlatformObjectUtils.isNotEmpty(scScMedicalList)){
                        scScMedicalList.forEach(entity->{
                            Map<String,Object> staticsMap = new HashMap<>();
                            staticsMap.put("num",atomicInteger4.getAndAdd(1));
                            staticsMap.put("name",entity.getScMedicalName());
                            staticsMap.put("doctorAmount",entity.getScMedicalDoctor());
                            staticsMap.put("nurseAmount",entity.getScMedicalNurse());
                            staticsMap.put("note",entity.getScMedicalNote());
                            scMedicalList.add(staticsMap);
                        });
                    }
                    samplingArea7.setMedicalList(scMedicalList);
                }else{
                    msg.append(areaList3.get(i).getProvince()).append(areaList3.get(i).getCity()).append(areaList3.get(i).getAreaNameBody()).append("未维护。应急备灾信息");
                }
            }
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
        SamplingSurveyReport report = SamplingSurveyReport.builder()
                .areaList(new ArrayList<>())
                .areaList2(new ArrayList<>())
                .areaList3(new ArrayList<>())
                .areaList4(new ArrayList<>())
                .areaList5(new ArrayList<>())
                .areaList6(new ArrayList<>())
                .areaList7(new ArrayList<>())
//                .disaterPictureList(new ArrayList<>())
//                .firePicPictureList(new ArrayList<>())
//                .reservoirPictureList(new ArrayList<>())
                .build();
        List<SamplingArea> townNameList = report.getAreaList();
        List<SamplingArea2> townNameList2 = report.getAreaList2();
        List<SamplingArea3> townNameList3 = report.getAreaList3();
        List<SamplingArea4> townNameList4 = report.getAreaList4();
        List<SamplingArea5> townNameList5 = report.getAreaList5();
        List<SamplingArea6> townNameList6 = report.getAreaList6();
        List<SamplingArea7> townNameList7 = report.getAreaList7();
        townNameList.addAll(areaList);
        townNameList2.addAll(areaList2);
        townNameList3.addAll(areaList3);
        townNameList4.addAll(areaList4);
        townNameList5.addAll(areaList5);
        townNameList6.addAll(areaList6);
        townNameList7.addAll(areaList7);
        reportList.add(report);
        paramMap.put("taskName",taskName);
        paramMap.put("provinceName",provinceName);
        paramMap.put("createTime",sdf.format(date));
        paramMap.put("samplingInfoList",samplingEntityMapList);
        paramMap.put("section1",reportList);
        if(PlatformObjectUtils.isNotEmpty(picMap) && PlatformObjectUtils.isNotEmpty( picMap.get("14"))){
            paramMap.put("gsPicture",new PictureRenderData(500, 320, picMap.get("14")));
        }else{
            paramMap.put("gsPicture",null);
        }

        // 生成文件
        AttachmentInfoEntity attach = attachmentInfoService.getAttach(attachId);
        String fileDirId = attach.getFileDirId();
        String attachPath = attach.getAttachPath();
        Map<String, String> resultMap = createReport(paramMap,modelName,attachPath,fileDirId);
        //--生成报告逻辑结束
        FieldReportManagement rp = new FieldReportManagement();
        FieldReportManagement fieldReportManagement = samplingSurveyReportRepository.getReportByTaskCode(taskCode);
        String reportId = "";
        if(PlatformObjectUtils.isNotEmpty(fieldReportManagement.getId())){
            reportId = fieldReportManagement.getId();
            //该任务已经存在过报告附件则更新 否则新增
            fieldReportManagement.setDefaultReportName(resultMap.get("docxName"));
            fieldReportManagement.setReportCreateTime(new Date());
            fieldReportManagement.setModelName(modelName);
            fieldReportManagement.setReportCreateUserId(PlatformSessionContext.getUserID());
            samplingSurveyReportRepository.update(fieldReportManagement);
            rp = fieldReportManagement;
        }else{
            FieldReportManagement reportManagement =new FieldReportManagement();
            String uuid = UUIDGenerator.getUUID();
            reportId = uuid;
            reportManagement.setId(uuid);
            reportManagement.setReportPath(resultMap.get("rootPath"));
            reportManagement.setDefaultReportName(resultMap.get("docxName"));
            reportManagement.setModelName(modelName);
            reportManagement.setReportCreateUserId(PlatformSessionContext.getUserID());
            //reportManagement.setReportCreateUserId("1");
            Date createDate = new Date();
            reportManagement.setReportCreateTime(createDate);
            samplingSurveyReportRepository.save(reportManagement);
            rp = reportManagement;
        }
        fieldSurveyTaskRepository.insertReportIdIntoTask(reportId,taskCode);
        Map<String,Object> finalMap = new HashMap<>();
        finalMap.put("rp",rp);
        finalMap.put("msg",msg);
        transReportMsgToCpxx(resultMap.get("rootPath")+File.separator+resultMap.get("docxName"),resultMap.get("docxName"),taskName+",现场调查报告");
        return RestResponse.succeed(finalMap);
    }
    //向产品信息服务传输生成的报告信息
    public void transReportMsgToCpxx(String picPath,String fileName,String keyword) throws Exception {
        String userId = PlatformSessionContext.getUserID();
        String userJson = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        //获取创建人单位
        String orgName = sUser.getOrgName();
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("cpxxRestUrl") + "/infAchievement/dockingOtherSystem";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Authorization", IdUtil.simpleUUID());
        //String picPath = "D:\\static\\预评估现场调查报告20231009.docx";
        File newfile = new File(picPath);
        Map<String, String> valueMap = new HashMap<>();
        valueMap.put("dataOrigin", "5");
        valueMap.put("publishingUnit", orgName);
        valueMap.put("createUser", userId);
        valueMap.put("achievementName", fileName);
        valueMap.put("keyword", keyword);
        Map<String, MultipartFile> fileParams = new HashMap<>();
        //本地文件转为MultipartFile
        MultipartFile file = RemoteTransfer.pathToMultipartFile(newfile);
        fileParams.put("file", file);
        String res = RemoteTransfer.uploadFile(url, fileParams, valueMap, null);
    }

    private Map<String, Object> buildFutureMap(SamplingEntity samplingEntity) {
        Map<String,Object> map = new HashMap<>(9);
        if(StringUtils.isNotBlank(samplingEntity.getHighFeature())){
            map.put("高层结构",samplingEntity.getHighFeature());
        }

        if(StringUtils.isNotBlank(samplingEntity.getSteelFeature())){
            map.put("钢结构",samplingEntity.getSteelFeature());
        }
        if(StringUtils.isNotBlank(samplingEntity.getConcreteFeature())){
            map.put("多层钢筋混凝土结构",samplingEntity.getConcreteFeature());
        }

        if(StringUtils.isNotBlank(samplingEntity.getMasonryFeature())){
            map.put("砖混结构",samplingEntity.getMasonryFeature());
        }

        if(StringUtils.isNotBlank(samplingEntity.getBrickWoodFeature())){
            map.put("砖木结构",samplingEntity.getBrickWoodFeature());
        }

        if(StringUtils.isNotBlank(samplingEntity.getSoilFeature())){
            map.put("土结构",samplingEntity.getSoilFeature());
        }
        if(StringUtils.isNotBlank(samplingEntity.getWoodFeature())){
            map.put("木结构",samplingEntity.getWoodFeature());
        }

        if(StringUtils.isNotBlank(samplingEntity.getStoneFeature())){
            map.put("石结构",samplingEntity.getStoneFeature());
        }

        if(StringUtils.isNotBlank(samplingEntity.getOtherFeature())){
            map.put("其他结构",samplingEntity.getOtherFeature());
        }
        return map;
    }

    @Override
    public Map<String, Object> getPage(ReportManagementVO vo, int curPage, int pageSize) {
        vo.setCreateUser(PlatformSessionContext.getUserID());
        return samplingSurveyReportRepository.findParentTask("0",vo, curPage, pageSize);
    }

    private void uploadFile(String fileName, String savePath,MultipartFile multipartFile) throws IOException {
        // 获取文件的后缀名
        assert fileName != null;
        //判断文件夹是否存在如果不存在则创建
        if(!new File(savePath).exists()){
            new File(savePath).mkdirs();
        }
        File file = new File(savePath, fileName);
        multipartFile.transferTo(file);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse uploadReport(MultipartFile file, String taskId) {
        FieldSurveyTaskEntity taskEntity = fieldSurveyTaskRepository.findById(taskId);
        String reportId = "";
        RestResponse restResponse = null;
        if (file==null) {
            restResponse = RestResponse.fail("上传失败，请选择文件");
            return restResponse;
        }
        try {
            //获取文件名称
            String fileName=file.getOriginalFilename();
            assert fileName != null;
            String filePrefix = fileName.split("\\.")[0];
            String fileType = fileName.split("\\.")[1];
            String localReportName = filePrefix+System.currentTimeMillis()+"."+fileType;
            //获取文件上传的本地路径
            String savePath = localDir;
            //构建文件

            //上传文件
//            uploadFile(fileName,savePath,file);
            uploadFile(localReportName,savePath,file);
            //构建实体类
            FieldReportManagement reportManagement = new FieldReportManagement();
            FieldHistoryUploadReport historyUploadReport = new FieldHistoryUploadReport();
            historyUploadReport.setReportName(fileName);
            historyUploadReport.setLocalReportName(localReportName);
            historyUploadReport.setReportPath(localDir);
            Date uploadTime = new Date();
            historyUploadReport.setUploadTime(uploadTime);

            reportManagement.setUserUploadReportName(fileName);
            reportManagement.setReportUploadUserId(PlatformSessionContext.getUserID());
            reportManagement.setReportUploadTime(uploadTime);
            reportManagement.setLocalUserUploadReportName(localReportName);

            if(StringUtils.isNotBlank(taskEntity.getReportId())){
                reportId = taskEntity.getReportId();
                reportManagement.setId(reportId);
                reportManagement.setReportPath(localDir);
                samplingSurveyReportRepository.updateUploadMassage(reportManagement);
            }else{
                //新增报告附件
                reportId =UUIDGenerator.getUUID();
                fieldSurveyTaskRepository.insertReportIdIntoTask(reportId,taskEntity.getTaskNum());
                reportManagement.setId(reportId);
                reportManagement.setReportPath(localDir);
                samplingSurveyReportRepository.saveUploadMassage(reportManagement);
            }
            //保存历史
            saveHistoryUploadReport(historyUploadReport,taskId);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("文件上传失败");
            return restResponse;
        }
        return RestResponse.succeed(samplingSurveyReportRepository.getReportById(reportId));
    }

    private void saveHistoryUploadReport(FieldHistoryUploadReport historyUploadReport,String taskId){
        //历史报告保存
        historyUploadReport.setId(UUIDGenerator.getUUID());
        historyUploadReport.setTaskId(taskId);
        historyUploadReport.setUploadUserId(PlatformSessionContext.getUserID());
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        historyUploadReport.setUploadUserName(sUser.getUserName());
        historyUploadReport.setOrgId(sUser.getOrgId());
        historyUploadReport.setOrgName(sUser.getOrgName());

        samplingSurveyReportRepository.saveHistoryUploadReport(historyUploadReport);
    }


    @Override
    public FieldReportManagement getReportByTaskId(String taskId) {
        return samplingSurveyReportRepository.getReportByTaskId(taskId);
    }

    @Override
    public void downloadReport(String reportId, String def, HttpServletResponse res) {
        FieldReportManagement report = samplingSurveyReportRepository.getReportById(reportId);
        String filePath = report.getReportPath();
        //todo 需要修改
        //filePath="D:\\static";
        String fileName = "";
        //def 1系统默认 2、用户自己的
        if("1".equals(def)){
            fileName = report.getDefaultReportName();
        }else{
            fileName = report.getLocalUserUploadReportName();
        }
        FileUploadUtil.download(filePath+File.separator+fileName,res);
    }


    @Override
    public Map<String, Object> getHistoryReportByTaskId(String taskId, int curPage, int pageSize) {
        return samplingSurveyReportRepository.getHistoryReportByTaskId(taskId,curPage,pageSize);
    }


    @Override
    public void downloadHistoryReport(String reportId, HttpServletResponse res) {
        FieldHistoryUploadReport report = samplingSurveyReportRepository.getHistoryUploadReportById(reportId);
        String filePath = report.getReportPath();
        String fileName = report.getLocalReportName();
        FileUploadUtil.download(filePath+File.separator+fileName,res);
    }

    @Override
    public List<FieldReportManagementVO> getFieldReport() {
        return samplingSurveyReportRepository.getFieldReport();
    }

    @Override
    public Map<String, Object> getReportListByTaskId(String taskId, int curPage, int pageSize) {
        return samplingSurveyReportRepository.getReportListByTaskId(taskId,curPage,pageSize);
    }

    @Override
    public FieldHistoryUploadReport getHistoryById(String xcdcReportId) {
        return samplingSurveyReportRepository.getHistoryUploadReportById(xcdcReportId);
    }

    private Map<String, Double> buildSortYearMap(SamplingEntity samplingEntity) {
        Map<String,Double> map = new HashMap<>(9);
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild70sBefore()) && Double.valueOf(samplingEntity.getBuild70sBefore())>0.0){
            map.put("1970年以前",Double.valueOf(samplingEntity.getBuild70sBefore()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild70s()) && Double.valueOf(samplingEntity.getBuild70s())>0.0){
            map.put("1971年-1980年",Double.valueOf(samplingEntity.getBuild70s()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild80s()) && Double.valueOf(samplingEntity.getBuild80s())>0.0){
            map.put("1981年-1990年",Double.valueOf(samplingEntity.getBuild80s()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild90s()) && Double.valueOf(samplingEntity.getBuild90s())>0.0){
            map.put("1991年-2000年",Double.valueOf(samplingEntity.getBuild90s()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild00s()) && Double.valueOf(samplingEntity.getBuild00s())>0.0){
            map.put("2001年-2010年",Double.valueOf(samplingEntity.getBuild00s()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild10s()) && Double.valueOf(samplingEntity.getBuild10s())>0.0){
            map.put("2011年-2015年",Double.valueOf(samplingEntity.getBuild10s()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild16s()) && Double.valueOf(samplingEntity.getBuild16s())>0.0){
            map.put("2016年-2020年",Double.valueOf(samplingEntity.getBuild16s()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild20s()) && Double.valueOf(samplingEntity.getBuild20s())>0.0){
            map.put("2021年及以后",Double.valueOf(samplingEntity.getBuild20s()));
        }
        List<Map.Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(map.entrySet());
//        Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
//
//            @Override
//            public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
//                return (int) (o2.getValue() - o1.getValue());
//            }
//        });
        Map result = new LinkedHashMap();
        for (Map.Entry<String, Double> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }


    private Map<String,Double> buildSortMap(SamplingEntity samplingEntity) {
        Map<String,Double> map = new HashMap<>(9);
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getHighStructure()) &&  Double.valueOf(samplingEntity.getHighStructure())>0.0){
            map.put("高层结构",Double.valueOf(samplingEntity.getHighStructure()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getSteelStructure()) && Double.valueOf(samplingEntity.getSteelStructure())>0.0){
            map.put("钢结构",Double.valueOf(samplingEntity.getSteelStructure()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getConcreteStructure()) && Double.valueOf(samplingEntity.getConcreteStructure())>0.0){
            map.put("多层钢筋混凝土结构",Double.valueOf(samplingEntity.getConcreteStructure()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getMasonryStructure()) && Double.valueOf(samplingEntity.getMasonryStructure())>0.0){
            map.put("砖混结构",Double.valueOf(samplingEntity.getMasonryStructure()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getBrickWoodStructure()) && Double.valueOf(samplingEntity.getBrickWoodStructure())>0.0){
            map.put("砖木结构",Double.valueOf(samplingEntity.getBrickWoodStructure()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getSoilStructure()) && Double.valueOf(samplingEntity.getSoilStructure())>0.0){
            map.put("土结构",Double.valueOf(samplingEntity.getSoilStructure()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getWoodStructure()) && Double.valueOf(samplingEntity.getWoodStructure())>0.0){
            map.put("木结构",Double.valueOf(samplingEntity.getWoodStructure()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getStoneStructure()) && Double.valueOf(samplingEntity.getStoneStructure())>0.0){
            map.put("石结构",Double.valueOf(samplingEntity.getStoneStructure()));
        }
        if(PlatformObjectUtils.isNotEmpty(samplingEntity.getOtherStructure()) && Double.valueOf(samplingEntity.getOtherStructure())>0.0){
            map.put("其他结构",Double.valueOf(samplingEntity.getOtherStructure()));
        }
        List<Map.Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
            @Override
            public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
                return (int) (o2.getValue() - o1.getValue());
            }
        });
        Map result = new LinkedHashMap();
        for (Map.Entry<String, Double> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    private List<Map<String, Object>> returnVillageStructureList(VillageTownHosPeoEntity hosPeo) {
        List<Map<String,Object>> villageStructureList = new ArrayList<>(9);
        Map<String,Object> townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "高层建筑");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageHighTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "钢结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageSteelTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "多层钢筋混凝土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageBetonTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖混结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageBrickTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageMasonryTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageSoilTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageWoodTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "石结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageStoneTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "其他结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageOtherTatio())+"%");
        villageStructureList.add(townStructureMap);
        return villageStructureList;
    }

    private List<Map<String, Object>> returnTownStructureList(VillageTownHosPeoEntity hosPeo) {
        List<Map<String,Object>> townStructureList = new ArrayList<>(9);
        Map<String,Object> townStructureMap = new HashMap<>();
        if(hosPeo.getDhpTownHighTatio().compareTo(BigDecimal.ZERO)>0){
            townStructureMap.put("structureTypeName", "高层建筑");
            townStructureMap.put("ratio", hosPeo.getDhpTownHighTatio() +"%");
            townStructureList.add(townStructureMap);
        }
        if(hosPeo.getDhpTownSteelTatio().compareTo(BigDecimal.ZERO)>0){
            townStructureMap = new HashMap<>();
            townStructureMap.put("structureTypeName", "钢结构");
            townStructureMap.put("ratio", hosPeo.getDhpTownSteelTatio() +"%");
            townStructureList.add(townStructureMap);
        }
        if(hosPeo.getDhpTownBetonTatio().compareTo(BigDecimal.ZERO)>0){
            townStructureMap = new HashMap<>();
            townStructureMap.put("structureTypeName", "多层钢筋混凝土结构");
            townStructureMap.put("ratio", hosPeo.getDhpTownBetonTatio() +"%");
            townStructureList.add(townStructureMap);
        }
        if(hosPeo.getDhpTownBrickTatio().compareTo(BigDecimal.ZERO)>0){
            townStructureMap = new HashMap<>();
            townStructureMap.put("structureTypeName", "砖混结构");
            townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownBrickTatio())+"%");
            townStructureList.add(townStructureMap);
        }
        if(hosPeo.getDhpTownMasonryTatio().compareTo(BigDecimal.ZERO)>0){
            townStructureMap = new HashMap<>();
            townStructureMap.put("structureTypeName", "砖木结构");
            townStructureMap.put("ratio", hosPeo.getDhpTownMasonryTatio() +"%");
            townStructureList.add(townStructureMap);
        }
        if(hosPeo.getDhpTownSoilTatio().compareTo(BigDecimal.ZERO)>0){
            townStructureMap = new HashMap<>();
            townStructureMap.put("structureTypeName", "土结构");
            townStructureMap.put("ratio", hosPeo.getDhpTownSoilTatio() +"%");
            townStructureList.add(townStructureMap);
        }
        if(hosPeo.getDhpTownWoodTatio().compareTo(BigDecimal.ZERO)>0){
            townStructureMap = new HashMap<>();
            townStructureMap.put("structureTypeName", "木结构");
            townStructureMap.put("ratio", hosPeo.getDhpTownWoodTatio() +"%");
            townStructureList.add(townStructureMap);
        }
        if(hosPeo.getDhpTownStoneTatio().compareTo(BigDecimal.ZERO)>0){
            townStructureMap = new HashMap<>();
            townStructureMap.put("structureTypeName", "石结构");
            townStructureMap.put("ratio", hosPeo.getDhpTownStoneTatio() +"%");
            townStructureList.add(townStructureMap);
        }
        if(hosPeo.getDhpTownOtherTatio().compareTo(BigDecimal.ZERO)>0){
            townStructureMap = new HashMap<>();
            townStructureMap.put("structureTypeName", "其他结构");
            townStructureMap.put("ratio", hosPeo.getDhpTownOtherTatio() +"%");
            townStructureList.add(townStructureMap);
        }
        townStructureList = townStructureList.stream().sorted((c1, c2) -> {
            Double count1 = Double.valueOf(c1.get("ratio").toString().replace("%",""));
            Double count2 = Double.valueOf(c2.get("ratio").toString().replace("%",""));
            return count1.compareTo(count2);        // 正序
//            return count2.compareTo(count1);        // 倒序
        }).collect(Collectors.toList());
        return townStructureList;
    }

    private List<Map<String, Object>> returnAreaVillageStructureList(HosPeoEntity hosPeo) {
        List<Map<String,Object>> villageStructureList = new ArrayList<>(9);
        Map<String,Object> townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "高层建筑");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageHighTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "钢结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageSteelTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "多层钢筋混凝土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageBetonTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖混结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageBrickTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageMasonryTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageSoilTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageWoodTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "石结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageStoneTatio())+"%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "其他结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageOtherTatio())+"%");
        villageStructureList.add(townStructureMap);
        return villageStructureList;
    }

    private List<Map<String,Object>> returnAreaTownStructureList(HosPeoEntity hosPeo){
        List<Map<String,Object>> townStructureList = new ArrayList<>(9);
        Map<String,Object> townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "高层建筑");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownHighTatio())+"%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "钢结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownSteelTatio())+"%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "多层钢筋混凝土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownBetonTatio())+"%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖混结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownBrickTatio())+"%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownMasonryTatio())+"%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownSoilTatio())+"%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownWoodTatio())+"%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "石结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownStoneTatio())+"%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "其他结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownOtherTatio())+"%");
        townStructureList.add(townStructureMap);
        return townStructureList;
    }
    private  Map<String, String> createReport(Map<String, Object> paramMap,String modelName,String attachPath,String fileDirId) {
        // 文件存放根目录
        String rootPath = localDir;
        File dir = new File(rootPath);
        // 文件夹不存在则创建
        if (!dir.exists()) {
            boolean mkdir = dir.mkdir();
        }
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowStr = sdf.format(now);
        String desFileName = "预评估现场调查报告" +nowStr+ ".docx";
        String docxPath =  rootPath +File.separator+ desFileName;
        // 根据模板渲染word、并且生成pdf文件
//        ClassPathResource classPathResource = new ClassPathResource(fileDirId+attachPath);
        try (InputStream inputStream = new FileInputStream(fileDirId + attachPath)) {
             //InputStream inputStream = new FileInputStream("D:\\static\\预评估现场调查报告模板-20231013.docx" ))  {
            //渲染表格  动态行
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            Configure config = Configure.newBuilder()
                    .bind("samplingInfoList", policy)
                    .bind("areaTownStructureList",policy)
                    .bind("areaVillageStructureList",policy)
                    .bind("townStructureList",policy)
                    .bind("villageStructureList",policy)
                    .bind("enterpriseList",policy)
                    .bind("gasStationList",policy)
                    .bind("statisticsList",policy)
                    .bind("staticsList",policy)
                    .bind("reservesList",policy)
                    .bind("rescueList",policy)
                    .bind("sanctuaryList",policy)
                    .bind("medicalList",policy)
                    .bind("equipList",policy).build();
            // 通过协查函模板，开始生成电子协查函
            try (
                XWPFTemplate template = XWPFTemplate.compile(inputStream,config).render(paramMap);
                OutputStream outDocx = Files.newOutputStream(Paths.get(docxPath))) {
                NiceXWPFDocument xwpfDocument = template.getXWPFDocument();
                // 输出word
                template.getXWPFDocument().write(outDocx);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>(4);
        map.put("rootPath", rootPath);
        map.put("docxName", desFileName);
        return map;
    }
}
